package com.windoent.yugioh.ui.activity.zixun;

import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.mobstat.StatService;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.google.gson.reflect.TypeToken;
import com.windoent.yugioh.R;
import com.windoent.yugioh.adapter.brvah.ZiXunSearchAdapter;
import com.windoent.yugioh.base.BaseActivity;
import com.windoent.yugioh.bean.ZiXunSearchBean;
import com.windoent.yugioh.constants.Constants;
import com.windoent.yugioh.http.PhoneLive;
import com.windoent.yugioh.utils.BaseMethod;
import com.windoent.yugioh.utils.BaseUtils;
import com.windoent.yugioh.utils.SharedPreUtil;
import com.windoent.yugioh.utils.ToastUtils;
import com.windoent.yugioh.widget.SearchView;
import com.windoent.yugioh.widget.dialog.SureNotDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import okhttp3.Call;

/**
 * author : robert
 * date   : 2021/5/7 10:43
 * desc   :
 */
public class ZiXunSearchActivity extends BaseActivity {
    private SearchView mSearch;
    private ImageView mIvDelete;
    private LinearLayout mLlDelete;
    private RecyclerView mRecyclerView;
    private ZiXunSearchAdapter adapter;
    private View mView;
    private LinearLayout mLlBack;


    @Override
    public int getLayout() {
        return R.layout.activity_zixun_search;
    }

    @Override
    public void initView() {
        super.initView();
        mView = (View) findViewById(R.id.view);
        immersiveStatusBar(mView);
        mLlBack = (LinearLayout) findViewById(R.id.ll_back);
        mSearch = (SearchView) findViewById(R.id.search);
        mIvDelete = (ImageView) findViewById(R.id.iv_delete);
        mLlDelete = (LinearLayout) findViewById(R.id.ll_delete);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    }

    @Override
    public void initData() {
        super.initData();
        initAdapter();
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onPageStart(this, "资讯搜索界面");
        getSearchHistoryData();
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPageEnd(this, "资讯搜索界面");
    }

    private void initAdapter() {
        FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(ZiXunSearchActivity.this);
        layoutManager.setFlexWrap(FlexWrap.WRAP);
        layoutManager.setFlexDirection(FlexDirection.ROW);
        layoutManager.setAlignItems(AlignItems.STRETCH);
        layoutManager.setJustifyContent(JustifyContent.FLEX_START);
        mRecyclerView.setLayoutManager(layoutManager);
        adapter = new ZiXunSearchAdapter();
//        String string = SharedPreUtil.getString(ZiXunSearchActivity.this, Constants.ZIXUN_SEARCH_LIST);
//        if (BaseMethod.notNull(string)) {
//            List<String> list = gson.fromJson(string,
//                    new TypeToken<List<String>>() {
//                    }.getType());
//            adapter.setNewInstance(list);
//        }
        mRecyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> baseQuickAdapter, @NonNull View view, int position) {
                List<String> data = adapter.getData();
                if (data != null) {
                    String s = data.get(position);
                    searchContent(s);
                }
            }
        });
    }

    @Override
    public void initListener() {
        super.initListener();
        mLlBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mSearch.getEditText().setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH || i == EditorInfo.IME_ACTION_UNSPECIFIED) {
                    //此处做逻辑处理
                    String text = mSearch.getEditStr();
//                    spSave(text);
                    searchContent(text);
                    return true;
                }
                return false;
            }
        });
        mLlDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //删除历史
                SureNotDialog dialog = new SureNotDialog(ZiXunSearchActivity.this);
                dialog.setTvContent(getString(R.string.string_clear_zixun_search_history));
                dialog.setYesOnclickListener(new SureNotDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        //yes
                        deleteNewsSearchHistory();
                    }
                });
                dialog.show();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
    }

    private void deleteNewsSearchHistory() {
        showLoadingDialog("");
        PhoneLive.deleteNewsSearchHistory(getUserToken(), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            getSearchHistoryData();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }


    private List<String> list = new ArrayList<>();

    //保存
    private void spSave(String text) {
        String string = SharedPreUtil.getString(ZiXunSearchActivity.this, Constants.ZIXUN_SEARCH_LIST);
        if (BaseMethod.notNull(string)) {
            list = gson.fromJson(string,
                    new TypeToken<List<String>>() {
                    }.getType());
        }
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            String str = iterator.next();
            if (BaseMethod.notNull(str) && str.equals(text)) {
                iterator.remove();
            }
        }
        if (list != null && list.size() > 10) {
            list.remove(list.size() - 1);
        }
        list.add(0, text);
        SharedPreUtil.put(ZiXunSearchActivity.this, Constants.ZIXUN_SEARCH_LIST, gson.toJson(list));
        adapter.setNewInstance(list);
    }

    private void getSearchHistoryData() {
        showLoadingDialog("");
        PhoneLive.getSearchHistoryData(getUserToken(), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            ZiXunSearchBean json = gson.fromJson(response, ZiXunSearchBean.class);
                            if (json != null) {
                                ZiXunSearchBean.DataBean data = json.getData();
                                if (data != null) {
                                    List<String> res = data.getRes();
                                    adapter.setNewInstance(res);
                                }
                            }

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //搜索
    private void searchContent(String text) {
        Intent intent = new Intent(ZiXunSearchActivity.this, ZiXunSearchListActivity.class);
        intent.putExtra("text", text);
        startActivity(intent);
    }

}
